package com.thx.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 线程上下文, set方法和get方法必须保证在同一线程中调用，才能保证放进去的值能正确取出.
 *
 * @author balance
 */
public class ThreadLocalContext {

  private static final ThreadLocal<Map<String, Object>> context =
      new ThreadLocal<Map<String, Object>>();
  private static Logger LOG = LoggerFactory.getLogger(ThreadLocalContext.class);


  /**
   * 清空线程上下文中缓存的变量.
   */
  public static void clear() {
    context.set(null);
  }

  /**
   * 在线程上下文中缓存变量.
   */
  public static void set(String key, Object value) {
    Map<String, Object> map = (Map<String, Object>) context.get();
    if (map == null) {
      map = new HashMap<String, Object>();
      context.set(map);
    }
    map.put(key, value);
  }

  /**
   * 从线程上下文中取出变量.
   */
  public static Object get(String key) {
    Map<String, Object> map = (Map<String, Object>) context.get();
    Object value = null;
    if (map != null) {
      value = map.get(key);
    }

    // LOG.debug("线程ID=" + Thread.currentThread().getId() + " key=" + key
    // + " value=" + value != null ? value.toString() : null);
    return value;
  }

  /**
   * 将变量移除.
   */
  public static void remove(String key) {
    Map<String, Object> map = (Map<String, Object>) context.get();
    if (map != null) {
      map.remove(key);
    }
  }

}
